import { useState, useEffect } from 'react';
import { Box, Typography, Card, CardContent, Button, Snackbar, Alert, CircularProgress } from '@mui/material';
import { FileDownload as DownloadIcon, Inbox as InboxIcon } from '@mui/icons-material';
import Breadcrumb, { BreadcrumbItem } from '../../components/Breadcrumb';
import { getExportOptions, exportFile, ExportOption } from '../../api/export';

// 面包屑导航配置
const breadcrumbItems: BreadcrumbItem[] = [{ title: '首页' }, { title: '信息导出管理' }];

const ExportManagement = () => {
    // 导出选项列表
    const [exportOptions, setExportOptions] = useState<ExportOption[]>([]);

    // 页面加载状态
    const [pageLoading, setPageLoading] = useState(true);

    // 导出按钮加载状态
    const [loading, setLoading] = useState<Record<string, boolean>>({});

    // 错误信息
    const [error, setError] = useState<string | null>(null);

    // Snackbar状态
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');

    // 获取导出选项列表
    useEffect(() => {
        const fetchExportOptions = async () => {
            try {
                setPageLoading(true);
                setError(null);

                // 调用API获取导出选项列表
                const options = await getExportOptions();
                setExportOptions(options);
            } catch (error) {
                console.error('获取导出选项列表失败:', error);
                setError('获取导出选项列表失败，请刷新页面重试');

                // 显示错误提示
                setSnackbarSeverity('error');
                setSnackbarMessage('获取导出选项列表失败，请刷新页面重试');
                setSnackbarOpen(true);
            } finally {
                setPageLoading(false);
            }
        };

        fetchExportOptions();
    }, []);

    // 处理导出
    const handleExport = async (option: ExportOption) => {
        try {
            // 设置加载状态
            setLoading((prev) => ({ ...prev, [option.export_id]: true }));

            // 显示导出中提示
            setSnackbarSeverity('info');
            setSnackbarMessage('正在准备导出文件...');
            setSnackbarOpen(true);

            // 调用导出函数
            await exportFile({
                export_id: option.export_id,
                export_desc: option.export_desc
            });

            // 显示成功提示
            setSnackbarSeverity('success');
            setSnackbarMessage('文件导出成功');
            setSnackbarOpen(true);
        } catch (error) {
            console.error(`导出${option.export_desc}失败:`, error);
            setSnackbarSeverity('error');
            setSnackbarMessage('导出失败，请稍后重试');
            setSnackbarOpen(true);
        } finally {
            // 清除加载状态
            setLoading((prev) => ({ ...prev, [option.export_id]: false }));
        }
    };

    // 处理Snackbar关闭
    const handleSnackbarClose = (_event?: React.SyntheticEvent | Event, reason?: string) => {
        if (reason === 'clickaway') {
            return;
        }
        setSnackbarOpen(false);
    };

    return (
        <Box sx={{ maxWidth: '1200px' }}>
            {/* 面包屑导航 */}
            <Box sx={{ mb: 3 }}>
                <Breadcrumb items={breadcrumbItems} />
            </Box>

            {/* 页面标题 */}
            <Box sx={{ mb: 4 }}>
                <Typography
                    variant="h4"
                    component="h1"
                    gutterBottom
                    sx={{
                        fontWeight: 'bold',
                        color: '#333',
                        mb: 1.5
                    }}>
                    信息导出管理
                </Typography>
                <Typography variant="body1" color="text.secondary" sx={{ mb: 1 }}>
                    在此页面可以导出各类学生信息，导出的文件格式为Excel(.xlsx)
                </Typography>
            </Box>

            {/* 页面加载状态 */}
            {pageLoading ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', my: 8 }}>
                    <CircularProgress size={60} />
                </Box>
            ) : error ? (
                <Alert severity="error" sx={{ my: 2 }}>
                    {error}
                </Alert>
            ) : exportOptions.length === 0 ? (
                /* 空状态 */
                <Box
                    sx={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        py: 8,
                        px: 2,
                        backgroundColor: '#f9f9f9',
                        borderRadius: '8px',
                        border: '1px dashed #ccc'
                    }}>
                    <InboxIcon
                        sx={{
                            width: '80px',
                            height: '80px',
                            opacity: 0.6,
                            mb: 2,
                            color: '#999'
                        }}
                    />
                    <Typography variant="h6" color="text.secondary" sx={{ mb: 1 }}>
                        暂无可导出的数据
                    </Typography>
                </Box>
            ) : (
                /* 导出选项卡片 */
                <Box
                    sx={{
                        display: 'flex',
                        flexWrap: 'wrap',
                        gap: 3,
                        mt: 2
                    }}>
                    {exportOptions.map((option) => (
                        <Box
                            key={option.export_id}
                            sx={{
                                width: { xs: '100%', sm: 'calc(50% - 12px)' },
                                minHeight: '180px',
                                display: 'flex'
                            }}>
                            <Card
                                variant="outlined"
                                sx={{
                                    width: '100%',
                                    display: 'flex',
                                    flexDirection: 'column',
                                    borderRadius: '8px',
                                    overflow: 'hidden',
                                    transition: 'transform 0.2s, box-shadow 0.2s',
                                    '&:hover': {
                                        transform: 'translateY(-4px)',
                                        boxShadow: '0 8px 16px rgba(0,0,0,0.1)'
                                    }
                                }}>
                                <CardContent
                                    sx={{
                                        flexGrow: 1,
                                        display: 'flex',
                                        flexDirection: 'column',
                                        p: 3
                                    }}>
                                    <Typography
                                        variant="h6"
                                        component="h2"
                                        gutterBottom
                                        sx={{
                                            fontWeight: 'bold',
                                            color: '#333',
                                            mb: 1.5
                                        }}>
                                        {option.export_desc}
                                    </Typography>
                                    <Button
                                        variant="contained"
                                        color="primary"
                                        startIcon={
                                            loading[option.export_id] ? (
                                                <CircularProgress size={20} color="inherit" />
                                            ) : (
                                                <DownloadIcon />
                                            )
                                        }
                                        onClick={() => handleExport(option)}
                                        disabled={loading[option.export_id]}
                                        fullWidth
                                        sx={{
                                            mt: 'auto',
                                            py: 1,
                                            borderRadius: '4px'
                                        }}>
                                        {loading[option.export_id] ? '导出中...' : '导出'}
                                    </Button>
                                </CardContent>
                            </Card>
                        </Box>
                    ))}
                </Box>
            )}

            {/* Snackbar提示 */}
            <Snackbar open={snackbarOpen} autoHideDuration={6000} onClose={handleSnackbarClose}>
                <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
                    {snackbarMessage}
                </Alert>
            </Snackbar>
        </Box>
    );
};

export default ExportManagement;
